package com.flute.framework.autoprompt;

import com.flute.framework.filesystem.FileDataBlock;
import com.flute.framework.monitor.EventLogger;
import com.flute.framework.util.ftp.IFileOperation;
import com.flute.tools.data.DataIterator;
import com.flute.tools.data.file.FileDataLineParser;
import com.flute.tools.data.file.FilesDataIterator;

public class FileTokenDataProvider implements ITokenDataProvider {

	private String folder;
	private IFileOperation oper;
	private static final String ADD = "add";
	private static final String DELETE = "delete";
	private static final String UPDATE = "update";
	private static final String INITIAL = "initial";

	public FileTokenDataProvider(String folder, IFileOperation oper) {
		setFolder(folder);
		setOper(oper);
	}

	public String getFolder() {
		return folder;
	}

	public void setFolder(String folder) {
		if (!folder.endsWith("/")) {
			folder = folder + "/";
		}
		this.folder = folder;
	}

	public IFileOperation getOper() {
		return oper;
	}

	public void setOper(IFileOperation oper) {
		this.oper = oper;
	}

	@Override
	public DataIterator<TokenData> getAddTokenDatas() {
		return getDataIterator(ADD);
	}

	@Override
	public DataIterator<TokenData> getDeleteTokenDatas() {
		return getDataIterator(DELETE);
	}

	@Override
	public DataIterator<TokenData> getInitialTokenDatas() {
		return getDataIterator(INITIAL);
	}

	@Override
	public DataIterator<TokenData> getUpdateTokenDatas() {
		return getDataIterator(UPDATE);
	}

	private FilesDataIterator<TokenData> getDataIterator(String key) {
		while (new FileDataBlock(folder + key, oper).isWriting()) {
			try {
				EventLogger.info("自动提示'" + folder + key + "'文件夹正在写入,等待5秒...",
						AutoPromptMonitor.getUpdateKey());
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		FilesDataIterator<TokenData> fdi = new FilesDataIterator<TokenData>(
				folder + key);
		fdi.setFilter(new PromptFileFilter());
		fdi.setParser(new FileDataLineParser<TokenData>(
				new TokenDataLineParser()));
		return fdi;
	}

	@Override
	public boolean isWriting() {
		return new FileDataBlock(folder, oper).isWriting();
	}

	@Override
	public void beginInital() {
		new FileDataBlock(folder + INITIAL, oper).startRead();
	}

	@Override
	public void beginUpdate() {
		new FileDataBlock(folder + UPDATE, oper).startRead();
	}

	@Override
	public void endInitial() {
		new FileDataBlock(folder + INITIAL, oper).removeReadLocks();
	}

	@Override
	public void endUpdate() {
		new FileDataBlock(folder + UPDATE, oper).removeReadLocks();
	}

}
